package com.edu.dsai.service.impl;
import com.edu.dsai.domain.History;
import com.edu.dsai.enums.SSEMsgType;
import com.edu.dsai.mapper.HistoryMapper;
import com.edu.dsai.service.OllamaService;
import com.edu.dsai.utils.SSEServer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;
@Service
@Slf4j
public class OllamaServiceImpl implements OllamaService {
    @Resource
    private OllamaChatClient ollamaChatClient;
    @Resource
    private HistoryMapper historyMapper;
    @Override
    public List<String> aiResponse(String userId, String msg) {
        Prompt prompt = new Prompt(new UserMessage(msg));
        Flux<ChatResponse> streamResponse = ollamaChatClient.stream(prompt);
        StringBuilder stringBuilder = new StringBuilder();
        List<String> list = streamResponse.toStream()
                                          .map(chatResponse -> {
                                              String content = chatResponse.getResult()
                                                                           .getOutput()
                                                                           .getContent();
                                              // 后端在控制台输入DS给予打字机文字回复信息
                                              log.info(content);
                                              stringBuilder.append(content);
                                              // 将DS的回复信息以流式方式通过SSE推送到前端
                                              SSEServer.sendMessage(userId.toString(), content, SSEMsgType.ADD);
                                              return content;
                                          })
                                          .toList();
        // 将生成的问答数据保存到数据库
        History history = new History();
        history.setMsg(msg);
        history.setAnswer(stringBuilder.toString());
        history.setUserName(userId);
        historyMapper.insert(history);
        return list;
    }
}
